package com.example.chartroom.controller;

import com.example.chartroom.mapper.FriendMapper;
import com.example.chartroom.mapper.UserMapper;
import com.example.chartroom.model.Friend;
import com.example.chartroom.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserMapper userMapper;
    @Resource
    FriendMapper friendMapper;
    @PostMapping("/login")
    public Object login(String username, String password, HttpServletRequest request){
        User user = userMapper.selectByName(username);
        if(user==null || !password.equals(user.getPassword())){
            log.info("user:{}",user);
            return new User("","");
        }
        HttpSession session = request.getSession(true);
        session.setAttribute("user", user);
        user.setPassword("");
        return user;
    }

    @PostMapping("/register")
    public Object register(String username, String password){
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
            user.setPassword("");
        }catch (DuplicateKeyException e){
            log.info("用户名重复，注册失败");
            user = new User("","");
        }
        return user;
    }

    @GetMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if(session == null){
            return new User();
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            return new User();
        }
        user.setPassword("");
        return user;
    }

    @GetMapping("/search")
    public Object getUserInfoByName(String searchValue, String selfUsername){
        if(searchValue != null) {
            User  user = userMapper.selectByName(selfUsername);
            List<Friend> friends = friendMapper.selectFriendList(user.getUserId());
            List<String> names = new ArrayList<>();
            for(Friend friend : friends){
                names.add(friend.getFriendName());
            }
            names.add(user.getUsername());
            List<String> res = userMapper.selectBySampleName(searchValue, names);
            return res;
        }
        return new ArrayList<User>();
    }
}
